package com.example.demo.security;

import com.alibaba.fastjson2.JSON;
import com.example.demo.core.Result;
import com.example.demo.core.SystemCode;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security 未登陆拦截处理
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Result<Void> result = Result.error(SystemCode.ERROR_UNAUTHORIZED, "未登陆");

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
        response.flushBuffer();
    }
}
